package com.test.mchelepesa.activity_fragment_rice;

import static android.Manifest.permission.READ_SMS;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.os.LocaleListCompat;

import com.test.mchelepesa.activity_fragment_rice.login_rice.LoginPhoneNumActivity_rice;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.GlobalConfig_rice;
import com.test.mchelepesa.constant_rice.Url_rice;
import com.test.mchelepesa.dialog_rice.LanguageDialog_rice;
import com.test.mchelepesa.dialog_rice.SmsStatementDialog_rice;
import com.test.mchelepesa.dialog_rice.UpdateDialog_rice;
import com.test.mchelepesa.util_rice.PermissionUtil_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.helper_rice.UserInfoHelper_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpDnsV2;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;
import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseApplication_rice;
import com.test.mchelepesa.util_rice.analytics_rice.util_rice.AnalyticsUtil_rice;

import java.util.List;
import java.util.TimeZone;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class MainActivity_rice extends BaseActivity_rice {

    private final String url = "https://play.google.com/store/apps/details?id=" + BaseApplication_rice.gApplication_rice().getPackageName();

    private SmsStatementDialog_rice smsStatementDialog;

    private final int CodeSMS = 45;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_rice);

        findViewById(R.id.activity_main_layout_login).postDelayed(this::initLanguage, 800);

    }

    private void initLanguage(){

        if ("Africa/Dar_es_Salaam".equalsIgnoreCase(TimeZone.getDefault().getID())) {
            if (TextUtils.isEmpty(UserInfoHelper_rice.getInstance().getLanguage())) {
                new LanguageDialog_rice(this, false, this::checkSms).show();
            } else {
                AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(
                        "sw".equalsIgnoreCase(UserInfoHelper_rice.getInstance().getLanguage()) ? "sw" : "en")
                );

                checkSms();
            }
        }else checkSms();

    }

    private void checkSms() {

        //检查权限是否全部同意
        if (!PermissionUtil_rice.checkLaunchPermissions(this, Manifest.permission.READ_SMS)&&smsStatementDialog==null) {

            smsStatementDialog = new SmsStatementDialog_rice(this, this::afterSms,
                    () -> EasyPermissions.requestPermissions(this,getString(R.string.launch_permissions_sms),CodeSMS, READ_SMS));
            smsStatementDialog.show();

        }else afterSms();

    }

    private void afterSms(){

        if (smsStatementDialog!=null && smsStatementDialog.isShowing()) smsStatementDialog.dismiss();

        findViewById(R.id.activity_main_layout_login).setOnClickListener(v -> {
            startResolver(() -> {
                //获取global配置
                HttpManager_rice.getInstance().queryGlobal();
            });
        });

        startResolver(() -> {
            //获取global配置
            HttpManager_rice.getInstance().queryGlobal();
        });

    }

    private void startResolver(@NonNull Runnable runnable) {

        if (!StaticConfig_rice.isTanz()) {
            runnable.run();
            return;
        }

        try {
            new Thread(() -> {
                HttpDnsV2 httpDnsV2 = new HttpDnsV2();
                httpDnsV2.lookupSys2(Url_rice.Url, new HttpDnsV2.Http3DnsCallback() {
                    @Override
                    public void onResult(String ipAddr) {
                        Url_rice.Url = "https://" + ipAddr;
//                        updateText("ip解析成功:" + ipAddr);

                        runnable.run();
                    }

                    @Override
                    public void onFailed(String msg) {
//                        updateText("ip解析失败:" + msg);

//                        runOnUiThread(() -> {
//                            new MsgDialog(MainActivity_rice.this, "Get Host Address Failed!!!\n" + msg, null).show();
//                        });
                    }
                });
            }).start();
        } catch (Exception e) {
            StringUtil_rice.printException(e);
        }
    }

    //查询Global配置信息响应
    public void onGlobalResponse() {

        runOnUiThread(() -> {

            int currentVersion = BaseApplication_rice.gApplication_rice().getVersionCode();

            if (currentVersion < GlobalConfig_rice.getInstance().getMinVersion()){
                //强制更新
                new UpdateDialog_rice(this,true,null).show();
                return;
            }else if (currentVersion < GlobalConfig_rice.getInstance().getLastVersion()){
                //提示更新
                new UpdateDialog_rice(this,false, this::process).show();
                return;
            }

            process();
        });
    }

    public void process() {

        try {
            AnalyticsUtil_rice.INSTANCE.init(BaseApplication_rice.gApplication_rice());
        } catch (Exception e) {
            StringUtil_rice.printException(e);
        }

        initLicense(
                findViewById(R.id.activity_main_view_license),
                findViewById(R.id.activity_main_license_logo),
                findViewById(R.id.activity_main_license_company_name));

        startActivityForSingleTop_rice(LoginPhoneNumActivity_rice.class);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (isClose()) return;
        if (requestCode == CodeSMS){
            afterSms();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (isClose()) return;
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms)){
            new AppSettingsDialog.Builder(this).build().show();
        }else if (requestCode == CodeSMS){
            afterSms();
        }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        if (isClose()) return;
        if (requestCode == CodeSMS){
            EasyPermissions.requestPermissions(this,getString(R.string.launch_permissions_sms),CodeSMS, Manifest.permission.READ_SMS);
        }
    }

}